package com.aifund.admin.service.impl;

import com.aifund.admin.entity.form.robot.RobotListForm;
import com.aifund.admin.entity.vo.PageResult;
import com.aifund.admin.entity.vo.robot.RobotPageVo;
import com.aifund.admin.enums.PageCodeEnum;
import com.aifund.admin.service.ExchangeService;
import com.aifund.admin.service.RobotService;
import com.aifund.common.dao.AiRobotDao;
import com.aifund.common.entity.AiRobot;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
public class RobotServiceImpl implements RobotService {

    @Autowired
    AiRobotDao robotDao;
    @Autowired
    ExchangeService exchangeService;

    @Override
    public PageResult<RobotPageVo> robotList(RobotListForm form) {
        Specification<AiRobot> specification = new Specification<AiRobot>() {
            @Override
            public Predicate toPredicate(Root<AiRobot> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        Sort sort = Sort.by(Sort.Direction.ASC,"createTime");
        Pageable pageable = PageRequest.of(form.getPageIndex()-1,form.getPageSize(),sort);
        Page<AiRobot> aiRobotPage = robotDao.findAll(specification, pageable);
        PageResult<RobotPageVo> pageResult = new PageResult<>();
        List<RobotPageVo> pageVos = new ArrayList<>();
        for(AiRobot aiRobot : aiRobotPage.getContent()){
            RobotPageVo vo = new RobotPageVo();
            BeanUtils.copyProperties(aiRobot,vo);
            vo.setExchangeName(exchangeService.getById(aiRobot.getExchangeId()).getExchangeName());;
            pageVos.add(vo);
        }
        pageResult.setCode(PageCodeEnum.SUCCESS.getCode());
        pageResult.setMsg(PageCodeEnum.SUCCESS.getMsg());
        pageResult.setCount(aiRobotPage.getTotalElements());
        pageResult.setData(pageVos);
        pageResult.setPage((form.getPageIndex()));
        pageResult.setLimit(form.getPageSize());
        return pageResult;
    }
}
